package com.ruoyi.mp.controller;

import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.mp.domain.MpTag;
import com.ruoyi.mp.service.IMpAccountService;
import com.ruoyi.mp.service.IMpTagService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 公众号标签Controller
 *
 * @author 2024-10-07 18:42
 * @date 2024-11-18
 */
@RestController
@RequestMapping("/tag")
public class MpTagController extends BaseController
{
    @Autowired
    private IMpTagService mpTagService;
    @Autowired
    private IMpAccountService iMpAccountService;
    @Autowired
    private WxMpService wxService;
    /**
     * 查询公众号标签列表
     */
    @RequiresPermissions("mp:tag:list")
    @GetMapping("/list")
    public TableDataInfo list(MpTag mpTag)
    {
        startPage();
        List<MpTag> list = mpTagService.selectMpTagList(mpTag);
        return getDataTable(list);
    }

    /**
     * 导出公众号标签列表
     */
    @RequiresPermissions("mp:tag:export")
    @Log(title = "公众号标签", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MpTag mpTag)
    {
        List<MpTag> list = mpTagService.selectMpTagList(mpTag);
        ExcelUtil<MpTag> util = new ExcelUtil<MpTag>(MpTag.class);
        util.exportExcel(response, list, "公众号标签数据");
    }

    /**
     * 获取公众号标签详细信息
     */
    @RequiresPermissions("mp:tag:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(mpTagService.selectMpTagById(id));
    }

    /**
     * 新增公众号标签
     */
    @RequiresPermissions("mp:tag:add")
    @Log(title = "公众号标签", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MpTag mpTag) throws WxErrorException {
                return toAjax(mpTagService.insertMpTag(mpTag));
    }

    /**
     * 修改公众号标签
     */
    @RequiresPermissions("mp:tag:edit")
    @Log(title = "公众号标签", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MpTag mpTag) throws WxErrorException {
      return toAjax(mpTagService.updateMpTag(mpTag));
    }

    /**
     * 删除公众号标签
     */
    @RequiresPermissions("mp:tag:remove")
    @Log(title = "公众号标签", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) throws WxErrorException {
        return toAjax(mpTagService.deleteMpTagByIds(ids));
    }


    @RequiresPermissions("mp:tag:refresh")
    @Log(title = "刷新公众号标签",businessType = BusinessType.UPDATE)
    @PostMapping("/accountId/{accountId}")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public  AjaxResult refresh(@PathVariable  Long accountId) throws WxErrorException {
        List<WxUserTag> wxUserTags =  wxService.switchoverTo(iMpAccountService.selectMpAccountById(accountId).getAppId()).getUserTagService().tagGet();
        List<MpTag> mpTags = new ArrayList<MpTag>();
        for (int i= 0; i<wxUserTags.size(); i++){
            MpTag mpTag = new MpTag();
            BeanUtils.copyProperties(wxUserTags.get(i),mpTag);
            mpTag.setAccountId(accountId);
            mpTag.setId(null);
            mpTag.setTagId(wxUserTags.get(i).getId());
            mpTag.setAppId(this.iMpAccountService.selectMpAccountById(accountId).getAppId());
            mpTag.setCount(Long.valueOf(wxUserTags.get(i).getCount()));
            mpTags.add(mpTag);
        }
        this.mpTagService.deleteTagsByAccountId(accountId);
        return toAjax(this.mpTagService.insertMpTagList(mpTags));
    }

    /**
     * 获取标签下粉丝列表
     */
    @RequiresPermissions("mp:tag:tagAllList")
    @Log(title = "公众号所有标签", businessType = BusinessType.DELETE)
    @GetMapping("/tagAllList/{ids}")
    public AjaxResult tagAllList(@PathVariable  Long ids) throws WxErrorException {
        String appId = this.iMpAccountService.selectMpAccountById(ids).getAppId();
        return success(mpTagService.selectAllMpTagList(appId));
    }

    /**
     * 获取标签下粉丝列表
     */
    @RequiresPermissions("mp:tag:userlist")
    @Log(title = "公众号标签", businessType = BusinessType.DELETE)
    @GetMapping("/tagUserlist/{ids}")
    public AjaxResult tagUserlist(@PathVariable Long ids) throws WxErrorException {
        return toAjax(mpTagService.tagUserlist(ids));
    }
}
